﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.Task.Data;
using CentralOffice.Task.BusinessActions;

using ApplicationTable = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsDataTable;
using ApplicationRow = CentralOffice.Task.Data.ApplicationDataSet.ApplicationsRow;

using ApprovalTable = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsDataTable;
using ApprovalRow = CentralOffice.Task.Data.ApprovalDataSet.ApprovalsRow;


namespace CentralOffice.WebClient.Tasks
{
    public partial class ApplicationEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlCategory, SiteConstants.ApprovalObject, false);
                ddlCategory.SelectedIndex = 0;

                SiteUtil.PopulateListBox(ddlUrgencyDegree, SiteConstants.Priority, false);
                ddlUrgencyDegree.SelectedIndex = 2;
                //SiteUtil.PopulateListBox(ddlSource, SiteConstants.TaskSources, false);

                //txtApplicant.Value = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
                //txtApplicantReadOnly.Value = txtApplicant.Value;

                txtApplicationCode.Text = Applications.GetMaxApplicationCode(DateTime.Now);

                lblApplicant.Text = CommonUtil.TrimAll(ApplicationContext.ActualUserName);


                //txtDateOfApplication.Text = DateTime.Now.ToString("yyyy-MM-dd");

                string id = HttpContext.Current.Request.QueryString["id"];
                if (!String.IsNullOrEmpty(id))
                {
                    SetFields(id);
                }
            }
        }

        private void SetFields(string applicationId)
        {
            ApplicationRow application = CentralOffice.Task.BusinessActions.Applications.GetById(new Guid(applicationId));

            //txtId.Text = application.Id;
            txtApplicationCode.Text = application.IsApplicationCodeNull() ? "" : application.ApplicationCode;
            txtName.Text = application.Name;
            //txtCategory.Text = application.Category;
            ddlCategory.SelectedValue = application.Category.ToString();//EnumUtil.GetInt32(SiteConstants.TaskPriority, CategoryDataSourceType.Xml, application.Status).ToString();
            ddlUrgencyDegree.SelectedValue = application.UrgencyDegree.ToString();
            //txtDateOfApplication.Text = application.DateOfApplication.ToString("yyyy-MM-dd");
            //txtApplicantReadOnly.Value = application.Applicant;
            //txtApplicant.Value = application.Applicant;
            lblApplicant.Text = application.Applicant;
            txtApprovalContent.Text = application.ApprovalContent;
            //txtStatus.Text = application.Status;
            
            //txtDescription.Text = application.Description;
            ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetFirstReply(application.Id);
            txtApprovedBy.Value = approval.ApprovedBy;
            txtApprovedByReadOnly.Value = approval.ApprovedBy;
            //txtApprovalContent.Text = approval.ContentText;
            chkIsFinal.Checked = approval.IsFinal;

            txtExecutor.Value = application.IsApplicationExecutorNull() ? "" : application.ApplicationExecutor;
            txtExecutorReadOnly.Value = txtExecutor.Value;
        }

        private ApplicationDataSet GetFields(string id, out ApprovalDataSet approvalDataSet)
        {
            ApplicationDataSet applicationDataSet = null;
            ApplicationRow application = null;

            approvalDataSet = new ApprovalDataSet();

            

            if (String.IsNullOrEmpty(id))
            {
                // new
                applicationDataSet = new ApplicationDataSet();
                application = applicationDataSet.Applications.NewApplicationsRow();
                SiteUtil.PopulateCommonField(application, Guid.NewGuid());
                application.Status = 1;//EnumUtil.GetInt32(SiteConstants.TaskPriority, CategoryDataSourceType.Xml, application.Status);
                //application.Applicant = txtApplicant.Value.Trim(SiteConstants.CommonSeparatorChar);

                AddApprovalRow(approvalDataSet, application.Id, Int32.Parse(ddlUrgencyDegree.SelectedValue), txtApprovedBy.Value, txtApprovalContent.Text, chkIsFinal.Checked);
            }
            else
            {
                // update
                application = CentralOffice.Task.BusinessActions.Applications.GetById(new Guid(id));

                ApprovalRow approval = CentralOffice.Task.BusinessActions.Approvals.GetFirstReply(new Guid(Request.QueryString["id"]));
                approvalDataSet = approval.Table.DataSet as ApprovalDataSet;
                int rejection = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "否决");
                // 如果是修改否决的申请，根据被否决的一步，添加一步新的审批步骤
                if (application.Status == rejection)
                {
                    ApprovalRow rejected = CentralOffice.Task.BusinessActions.Approvals.GetRejectedStep(new Guid(Request.QueryString["id"]));
                    AddApprovalRow(approvalDataSet, application.Id, Int32.Parse(ddlUrgencyDegree.SelectedValue), rejected.ApprovedBy, txtApprovalContent.Text, chkIsFinal.Checked);
                    // 如果是修改否决的申请，修改申请状态
                    application.Status = EnumUtil.GetInt32(SiteConstants.ApprovalStatus, CategoryDataSourceType.Xml, "待审");
                }
                else
                {
                    // 修改第一个审批步骤的信息
                    approval.ApprovedBy = txtApprovedBy.Value;//, , 
                    approval.ContentText = txtApprovalContent.Text;
                    approval.IsFinal = chkIsFinal.Checked;

                    if (approval.IsNextStepIsApprovedNull())
                    {
                        approval.NextStepIsApproved = false;
                    }
                    if (approval.IsSequenceNumberNull())
                    {
                        approval.SequenceNumber = 1;
                    }
                }
                applicationDataSet = application.Table.DataSet as ApplicationDataSet;
            }

            application.ApplicationCode = txtApplicationCode.Text;
            application.Name = txtName.Text;
            application.Category = Int32.Parse(ddlCategory.SelectedValue);
            application.UrgencyDegree = Int32.Parse(ddlUrgencyDegree.SelectedValue);

            //application.DateOfApplication = txtDateOfApplication.Text.Length == 0 ? DateTime.Now : DateTime.Parse(txtDateOfApplication.Text).AddHours(DateTime.Now.Hour).AddMinutes(DateTime.Now.Minute).AddSeconds(DateTime.Now.Second);
            application.DateOfApplication = DateTime.Now;
            //application.Applicant = txtApplicant.Value.Trim(SiteConstants.CommonSeparatorChar);
            application.Applicant = CommonUtil.TrimAll(ApplicationContext.ActualUserName);
            application.ApprovalContent = txtApprovalContent.Text;
            application.ApplicationExecutor = txtExecutor.Value;

            string fileName = SaveFile(SiteUtil.GetTaskFilesPath(), fileAttachments);
            if (fileName.Length > 0)
            {
                application.Attachments = fileName;
            }

            if (String.IsNullOrEmpty(id))
            {
                applicationDataSet.Applications.AddApplicationsRow(application);
            }

            return applicationDataSet;
        }

        private string SaveFile(string rootDir, FileUpload file)
        {
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {
                //file.SaveAs(path + file.FileName);
                //fileName = rootDir + file.FileName;
                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                file.SaveAs(fn);
                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);
            }
            else
            {
                
            }
            return fileName;
        }

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = null;
            LinkButton btn = sender as LinkButton;
            if (btn != null)
            {
                txtSelectedObject.Value = btn.CommandName;

                if (btn.CommandName == "Executor")
                {
                    assignedBy = txtExecutor.Value.Split(',');
                }
                else
                {
                    assignedBy = txtApprovedBy.Value.Split(',');
                }
            }

            tvEmp.Nodes.Clear();
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);//null 

            updPnlDepartment.Update();
            mdlDetailView.Show();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            //Guid taskId = this.Save();

            //ClearFields();
            string applicationId = HttpContext.Current.Request.QueryString["id"];

            if (String.IsNullOrEmpty(applicationId) && txtApplicationCode.Text.Trim().Length > 0)
            {
                bool exist = CentralOffice.Task.BusinessActions.Applications.IsExistApplicationCode(txtApplicationCode.Text.Trim());
                if (exist)
                {
                    lblJavaScript.Text = "<script type=\"text/javascript\">alert('申请编号已存在，请修改！');</script>";
                    return;
                }
            }

            ApprovalDataSet approvalDataSet;
            
            ApplicationDataSet applicationDataSet = GetFields(applicationId, out approvalDataSet);

            CentralOffice.Task.BusinessActions.Applications.Update(applicationDataSet, approvalDataSet);

            if(String.IsNullOrEmpty(applicationId))
            {
                applicationId = (applicationDataSet.Applications.Rows[0] as ApplicationRow).Id.ToString();
            }

            Response.Redirect("ApplicationView.aspx?id=" + applicationId.ToString());
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string employees = "";
            string employeesId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        employees += node.Text + ",";
                        employeesId += node.Value + ",";
                    }
                }
            }
            if (txtSelectedObject.Value == "Executor")
            {
                //txtApplicantReadOnly.Value = employees.Trim(',');
                txtExecutorReadOnly.Value = employees.Trim(',');
                txtExecutor.Value = employees.Trim(',');
            }
            else
            {
                txtApprovedByReadOnly.Value = employees.Trim(',');
                //txtApprovedBy.Value = departmentsId;
                txtApprovedBy.Value = employees.Trim(',');
            }
        }

        private static void AddApprovalRow(ApprovalDataSet approvalDataSet, Guid applicationId, int urgencyDegree, string approvedBy, string approvedContext, bool isFinal)
        {
            ApprovalRow approval = approvalDataSet.Approvals.NewApprovalsRow();
            SiteUtil.PopulateCommonField(approval, Guid.NewGuid());

            approval.ApplicationId = applicationId;
            approval.ApprovedBy = approvedBy;
            //approval.DateApproved = txtDateApproved.Text;
            approval.ContentText = approvedContext;
            //approval.Opinion = txtOpinion.Text;
            //approval.ResultApproved = txtResultApproved.Text;
            //approval.PreviousStep = txtPreviousStep.Text;
            approval.IsFinal = isFinal;
            approval.NextStepIsApproved = false;
            approval.IsApproved = false;
            approval.SequenceNumber = 1;
            approval.ElapsedTime = 0;

            string interval = SiteUtil.GetConfigurationItem(urgencyDegree, SiteConstants.Priority).Data;
            approval.WarningDate = DateTime.Now.AddMinutes(Convert.ToDouble(interval));

            approvalDataSet.Approvals.AddApprovalsRow(approval);
        }

        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }
    }
}